package com.example.myapplication.util;
import android.text.TextUtils;
import android.util.Log;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


public class HttpClientUtils {

    /**
     * 获取网页的html源代码
     * @param path 请求路径
     * @return
     * @throws Exception
     */
    public static String getHtml(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == 200) {
            InputStream in = conn.getInputStream();
            byte[] data = toByteArray(in);
            String html = new String(data, "UTF-8");
            return html;
        }
        return null;
    }

    /**
     * 转字节
     * @param input
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*4];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

    /**
     * Android的get请求
     * @param url 请求链接
     * @return
     */
    public static String useHttpUrlConnectionGet(String url){
        try {
            URL netUrl=new URL(url);//获取服务器地址
            HttpURLConnection urlConnection= (HttpURLConnection) netUrl.openConnection();//双方建立连接
            urlConnection.setRequestMethod("GET");//给服务器发送请求
            //服务器返回的数据 我们需要返回的是文本   所以返回的数据默认是字节流
            InputStream inputStream=urlConnection.getInputStream(); //字节流
            int code = urlConnection.getResponseCode();
            Reader reader=new InputStreamReader(inputStream); //把字节流转化成字符流
            BufferedReader bufferedReader=new BufferedReader(reader);//字符流 转成 缓冲流，一次可以读一行
            String result = "";
            String temp;
            //当temp读到的数据为空就结束
            while ((temp = bufferedReader.readLine()) != null){
                result += temp;
                Log.i("GET请求结果", "请求状态码:" + code + "\n请求结果:\n" + result);

            }
            inputStream.close();
            reader.close();
            bufferedReader.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取http连接
     * @param url
     * @return
     */
    public static HttpURLConnection getHttpURLConnection(String url) throws IOException {
        HttpURLConnection mHttpURLConnection=null;
        try {
            URL mUrl=new URL(url);
            mHttpURLConnection=(HttpURLConnection)mUrl.openConnection();
            //设置链接超时时间
            mHttpURLConnection.setConnectTimeout(15000);
            //设置读取超时时间
            mHttpURLConnection.setReadTimeout(15000);
            //设置请求参数
            mHttpURLConnection.setRequestMethod("POST");
            //添加Header
            mHttpURLConnection.setRequestProperty("Connection","Keep-Alive");
            //接收输入流
            mHttpURLConnection.setDoInput(true);
            //传递参数时需要开启
            mHttpURLConnection.setDoOutput(true);
        } catch (IOException e) {
            Log.i("POST请求结果", "网络连接失败！");
            e.printStackTrace();
        }
        return mHttpURLConnection ;
    }

    /**
     * Android的post请求
     * @param url 路径
     * @param postParams 入参
     * @return
     */
    public static String useHttpUrlConnectionPost(String url,List<NameValuePair> postParams) throws IOException {
        InputStream mInputStream;
        HttpURLConnection mHttpURLConnection = getHttpURLConnection(url);
        try {
            //HttpURLConnection.getOutputStream输出流 请求
            postParams(mHttpURLConnection.getOutputStream(), postParams);
            //HttpURLConnection.connect 连接
            mHttpURLConnection.connect();
            // HttpURLConnection.getInputStream输入流 响应
            mInputStream = mHttpURLConnection.getInputStream();
            int code = mHttpURLConnection.getResponseCode();
            String response = coverStreamToString(mInputStream);
            Log.i("POST请求结果", "请求状态码:" + code + "\n请求结果:\n" + response);
            mInputStream.close();
            return response;
        } catch (IOException e) {
            Log.i("POST请求结果", "网络连接失败！");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * post请求拼接参数
     * @param output
     * @param paramsList
     * @throws IOException
     */
    public static void postParams(OutputStream output,List<NameValuePair>paramsList) throws IOException {
        StringBuilder mStringBuilder=new StringBuilder();
        for (NameValuePair pair:paramsList){
            if(!TextUtils.isEmpty(mStringBuilder)){
                mStringBuilder.append("&");
            }
            mStringBuilder.append(URLEncoder.encode(pair.getName(),"UTF-8"));
            mStringBuilder.append("=");
            mStringBuilder.append(URLEncoder.encode(pair.getValue(),"UTF-8"));
        }
        BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(output,"UTF-8"));
        writer.write(mStringBuilder.toString());
        writer.flush();
        writer.close();
    }

    /**
     * 流转字符串
     * @param mInputStream
     * @return
     */
    private static String coverStreamToString(InputStream mInputStream) {
        InputStreamReader inputStreamReader = null;
        StringBuffer buffer = new StringBuffer();
        try {
            inputStreamReader = new InputStreamReader(mInputStream, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String str = null;
        while (true) {
            try {
                if ((str = bufferedReader.readLine()) == null) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            buffer.append(str);
        }
        return buffer.toString();
    }

    /**
     *
     * @param connection
     * @param jsr
     * @return
     */
    public static String getReturn(HttpURLConnection connection,String jsr){
        try{
            StringBuffer buffer = new StringBuffer();
            if(jsr != null){
                byte[] bytes = jsr.getBytes();
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(bytes);
                outputStream.flush();
                outputStream.close();
            }
            //将返回的输入流转换成字符串
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            return buffer.toString();
        }catch (Exception e){
            Log.i("err","postUrlConnection出错" + e);
        }
        return null;
    }

    /**
     * post请求
     * @param url
     * @param params 传json格式
     * @return
     */
    public static String getPost(String url,String params){
        URL serverUrl = null;
        try {
            serverUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) serverUrl.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 设置是否向connection输出，因为这个是post请求，参数要放在
        // http正文内，因此需要设为true
        conn.setDoOutput(Boolean.TRUE);
        conn.setDoInput(Boolean.TRUE);
        //请求方式是POST
        try {
            conn.setRequestMethod("POST");
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
        // Post 请求不能使用缓存
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-type", "application/json");
        //必须设置false，否则会自动redirect到重定向后的地址
        conn.setInstanceFollowRedirects(false);
        //建立连接
        try {
            conn.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取了返回值
        String result = getReturn(conn,params);
        return result;
    }
}
